package com.realtyManage.springboot.Interceptor;

import com.realtyManage.springboot.Service.IAuthUserService;
import com.realtyManage.springboot.Service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义拦截器
 * 拦截自定义Token并与服务端进行比较
 *
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/5/28
 **/
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    private final Logger log = LoggerFactory.getLogger(AuthorizationInterceptor.class);

    @Autowired
    private IAuthUserService iAuthUserService;

    @Autowired
    private UserServiceImpl userServiceImpl;

    //拦截小程序和后台管理系统
    private static final String[] requestUrls = new String[]{"/user/", "/management/"};

    //在执行handler之前来执行的
    //用于用户认证校验、用户权限校验
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验用户权限变更
        String phone = request.getSession().getAttribute("user").toString();
        Integer level = Integer.parseInt(request.getSession().getAttribute("level").toString());
        if(!userServiceImpl.findByTelePhone(phone).getLevel().equals(level)){
            response.setHeader("Authorization", "");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "用户权限变更，重新登录");
        }

        /*BaseEntity base = new BaseEntity();
        boolean ajaxFlag = false;
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            ajaxFlag = true;
        }
        // 路径带工程
        String requestURI = request.getRequestURI();
        // 路径不带工程
        String requestPATH = request.getServletPath();
        //获取AuthUserId
        String uid = request.getHeader("uid");
        //取的头部文件中的Token
        //Token加密规则：Md5(用户手机号+密码+SALT)
        String token = request.getHeader("token");
        if(uid == null || uid == "" || token == null || token == "") {
            base.setInfoCode(103);
            base.setInfoText(SysExecRsUtil.getMsgFromCode(103));
            String jsonObjectStr = JSONObject.toJSONString(base);
            returnJson(response, jsonObjectStr);
            return false;
        }

        Optional<AuthUser> authUserOptional = iAuthUserService.findById(Integer.parseInt(uid));
        if(authUserOptional.isPresent()){
            //用户正确
            if(!authUserOptional.get().getToken().isEmpty() && authUserOptional.get().getToken().equals(token)){
                //权限正确
                //TODO 用户权限处理
                return true;
            }else {
                base.setInfoCode(102);
                base.setInfoText(SysExecRsUtil.getMsgFromCode(102));
                String jsonObjectStr = JSONObject.toJSONString(base);
                returnJson(response,jsonObjectStr);
                return false;
            }
        }else{
            base.setInfoCode(101);
            base.setInfoText(SysExecRsUtil.getMsgFromCode(101));
            String jsonObjectStr = JSONObject.toJSONString(base);
            returnJson(response,jsonObjectStr);
            //如果返回false表示拦截不继续执行handler，如果返回true表示放行
            return false;
        }*/

        //权限管理使用过滤器，暂时去掉拦截器
        return true;

        /*String orderIdStr = null;
        if (requestURI != null) {
            for (String url : requestUrls) {
                if (requestURI.indexOf(url) != -1) {
                    orderIdStr = requestURI.substring(requestURI.indexOf(url) + url.length());
                    char[] chars = orderIdStr.toCharArray();
                    for (int i = 0; i < chars.length; i++) {
                        if (!Character.isDigit(chars[i])) {
                            orderIdStr = orderIdStr.substring(0, i);
                            break;
                        }
                    }
                }
            }

            if (orderIdStr != null) {
                Integer orderId;
                try {
                    orderId = Integer.parseInt(orderIdStr);
                } catch (Exception e) {
                    log.error("状态拦截器订单id转换异常,orderId:" + orderIdStr + ",链接:" + requestURI, e);
                    return false;
                }

                //查询订单状态
                OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);
                //订单是否已经回到身份验证
                if (StatusConstant.ORDER_VERIFY_IDCARD.equals(orderInfo.getStatus())){
                    log.error("状态拦截器订单已超过48小时，回到身份验证状态,orderId:" + orderIdStr + ",链接:" + requestURI);
                    //if (ajaxFlag){
                    //    response.setHeader("orderStatus", "expire");
                    //}else {
                    //    response.sendRedirect(expireUrl);
                    //}
                    //return false;
                    BaseResult baseResult = new BaseResult();
                    baseResult.setCode(0);
                    baseResult.setMessage("订单状态变更，请重新操作");
                    baseResult.setData(StatusConstant.ORDER_VERIFY_IDCARD);


                    String jsonObjectStr = JSONObject.toJSONString(baseResult);
                    returnJson(response,jsonObjectStr);

                    //如果返回false表示拦截不继续执行handler，如果返回true表示放行
                    return false;
                }
            }
        }
        return true;*/

        /*
        //判断是否是公开 地址
        //实际开发中需要公开 地址配置在配置文件中
        //...
        if(url.indexOf("login.action")>=0){
            //如果是公开 地址则放行
            return true;
        }

        //判断用户身份在session中是否存在
        HttpSession session = request.getSession();
        String usercode = (String) session.getAttribute("usercode");
        //如果用户身份在session中存在放行
        if(usercode!=null){
            return true;
        }
        //执行到这里拦截，跳转到登陆页面，用户进行身份认证
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);

        //如果返回false表示拦截不继续执行handler，如果返回true表示放行
        return false;*/

        /*Object user = request.getSession().getAttribute("user");
        if (user == null || user.equals(""))  {
            response.sendRedirect("/index.html");
            return false;
        }
        return true;*/
    }

    //在执行handler返回modelAndView之前来执行
    //如果需要向页面提供一些公用 的数据或配置一些视图信息，使用此方法实现 从modelAndView入手
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("HandlerInterceptor1...postHandle");
    }

    //执行handler之后执行此方法
    //作系统 统一异常处理，进行方法执行性能监控，在preHandle中设置一个时间点，在afterCompletion设置一个时间，两个时间点的差就是执行时长
    //实现 系统 统一日志记录
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除所有session
        request.getSession().invalidate();
        System.out.println("HandlerInterceptor1...afterCompletion");
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            log.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
